package com.security.control.core.authentication.mobile;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * @author imoot@gamil.com
 * @date 2019/1/2 0002 9:59
 * 短信登录的验证逻辑（由于短信验证码的验证在过滤器中已完成，这里直接读取用户信息）
 */
public class SmsValidateCodeAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    //进行身份认证的逻辑
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SmsValidateCodeAuthenticationToken authenticationToken = (SmsValidateCodeAuthenticationToken) authentication;
        UserDetails user = userDetailsService.loadUserByUsername((String) authenticationToken.getPrincipal());//通过手机号获取用户信息
        if (null == user) {
            throw new InternalAuthenticationServiceException("无法获取用户信息");
        }
        SmsValidateCodeAuthenticationToken authenticationResult = new SmsValidateCodeAuthenticationToken(user, user.getAuthorities());
        authenticationResult.setDetails(authenticationToken.getDetails());//把未认证的用户信息拷贝到已认证的用户信息中
        return authenticationResult;
    }

    //判断是否为本provider支持的token
    @Override
    public boolean supports(Class<?> authentication) {
        return SmsValidateCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public UserDetailsService getUserDetailsService() {
        return userDetailsService;
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }
}
